import { message, Result, Spin, Button } from 'antd';
import { runApp, IAppConfig, history } from 'ice';
import user from './apis/user';
import { clearJump, getRoutePath } from './utils/navigator';
import { isLogin } from './utils/common';
import { NoNeedLoginPath } from './config/index';
import store from '@/store';

const appConfig: IAppConfig = {
  app: {
    rootId: 'root',
    errorBoundary: true,
    ErrorBoundaryFallback: function () {
      return (
        <Result
          status="500"
          title="500"
          subTitle="对不起,页面出现错误,请联系开发人员！"
          extra={
            <Button type="primary" onClick={() => clearJump('/')}>
              返回主页
            </Button>
          }
        />
      );
    },
    onErrorBoundaryHandler(error, componentStack) {
      console.error(error);
    },
    onLaunch: (options) => {
      const path = getRoutePath();
      if (isLogin()) {
        // 路径包含了需要登录的界面则自动跳转到主页
        if (NoNeedLoginPath.indexOf(path) > -1) {
          clearJump('/');
        }
      } else {
        if (NoNeedLoginPath.indexOf(path) == -1) {
          clearJump('/login');
        }
      }
      history?.listen((location, action) => {
        const path = getRoutePath();
        if (isLogin()) {
          // 路径包含了需要登录的界面则自动跳转到主页
          if (NoNeedLoginPath.indexOf(path) > -1) {
            setTimeout(() => {
              clearJump('/');
            }, 1000);
          }
        } else {
          if (NoNeedLoginPath.indexOf(path) == -1) {
            setTimeout(() => {
              clearJump('/login');
            }, 1000);
          }
        }
      });
    },
    getInitialData: async (ctx) => {
      const path = getRoutePath();
      if (NoNeedLoginPath.indexOf(path) > -1) {
        return;
      }
      const data = await user.getUserInfo();
      return {
        initialStates: {
          global: { user: data },
        },
      };
    },
    onError: (error: Error) => {
      console.log(error);
    },
  },
  router: {
    type: 'hash',
    fallback: (
      <Spin
        spinning
        tip="加载中"
        style={{
          width: '100%',
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      ></Spin>
    ),
  },
  request: {
    baseURL: '',
    timeout: 3000,
    withCredentials: true,
    responseType: 'json',
    method: 'POST',
    withFullResponse: true,
    interceptors: {
      request: {
        onConfig: async (config) => {
          return config;
        },
        onError: async (error) => {},
      },
      response: {
        onConfig: async (response) => {
          return response;
        },
        onError: async (error) => {
          if (!error.response) {
            message.error(error.message || '请求错误,请检查网络状态');
            return;
          }
          const data = error.response?.data;
          const status = error.response?.status;
          const [state, dispatch] = store.getModel('security');
          if (status == 403) {
            if (state.isFirst) {
              clearJump('/login');
              dispatch.save({
                isFirst: false,
              });
            } else {
              dispatch.save({
                needLogin: true,
              });
            }
          }
          message.error(data.message || '服务器错误');
        },
      },
    },
  },
};

runApp(appConfig);
